//
//  SinaNetWorksManager.swift
//  Sina
//
//  Created by 星仔 on 2017/3/20.
//  Copyright © 2017年 xingZai. All rights reserved.
//

import UIKit
import AFNetworking

enum HttpMethod:String{
    
    case GET
    case POST
}

class SinaNetWorksManager: AFHTTPSessionManager {
    
    /// 访问令牌，所有的网络都基于此，(登录除外)
    let acctoken:String? = "2.00lqNlIDuAFoWD651abd6d13uawdoB"
    static let shareNetWorkManager = SinaNetWorksManager()
}
//MARK：处理token请求,首先先判断token是否存在，然后再判断字典参数是否存在，
extension SinaNetWorksManager{
     //token因为好多地方都要用，所以把它单独写出来来处理
    func requestToken(httpMethod:HttpMethod = .GET,urlString:String,parameters:[String:Any]?,completion:@escaping((_ json:AnyObject?,_ isSuccess:Bool)->())){
        //判断token是否为空，如果为空返回
        guard let  acctoken = acctoken else{
            
            print("token为空，请登录")
            completion(nil,false)
            return
        }
        
        var parameter = parameters
        if parameter == nil {//如果没有字典，重新创建一个
            parameter = [String:Any]()
        }
        //设置accessToken
        parameter?["access_token"] = acctoken
        requestData(urlString: urlString, parameters: parameters, completion: completion)
    }
}
//MARK: 请求微博状态
extension SinaNetWorksManager{
    func requestData(httpMethod:HttpMethod = .GET,urlString:String,parameters:[String:Any]?,completion:@escaping ((_ json:AnyObject?,_ isSuccess:Bool)->())){
        
        let success = {(task:URLSessionDataTask,json:Any?) -> () in
            completion(json as AnyObject? , true);
        }
        let failure = {(task:URLSessionDataTask?,error:Error) -> () in
            
            if (task?.response as! HTTPURLResponse).statusCode == 403{
                print("token已过期，请登录")
            }
            completion(nil, false)
        }
        if httpMethod == .GET {
            get(urlString, parameters: parameters, progress: nil
                , success:success, failure: failure)
        }else{
            post(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
